package com.es.easystoragesimulatedata.controller;

import com.es.easystoragesimulatedata.model.*;
import com.es.easystoragesimulatedata.service.StationDataService;
import com.es.easystoragesimulatedata.service.StationInfoService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.CrossOrigin;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 电站运行数据控制器
 * 负责处理电站运行数据相关的接口，包括：
 * - 单站运行数据查询
 * - 电站概览数据查询  
 * - 电站排名数据查询
 */
@Slf4j
@RestController
@RequestMapping("/api/stations")
@Tag(name = "电站运行数据管理", description = "电站运行数据查询和分析相关接口")
@CrossOrigin(origins = "*", allowCredentials = "false", maxAge = 3600)
@RequiredArgsConstructor
public class StationDataController {
    
    private final StationDataService stationDataService;
    private final StationInfoService stationInfoService;
    
    /**
     * 根据电站ID获取单站运行数据
     */
    @GetMapping("/{stationId}")
    @Operation(
        summary = "获取单站运行数据", 
        description = "根据电站ID获取单站运行数据，支持按日期范围过滤。日期格式为yyyy-MM-dd。"
    )
    @ApiOperationSupport(order = 21)
    public ResponseEntity<Map<String, Object>> getStationData(
            @Parameter(description = "电站ID", required = true, example = "ST001")
            @PathVariable String stationId,
            @Parameter(description = "开始日期，格式：yyyy-MM-dd", example = "2025-01-20")
            @RequestParam(required = false) String startDate,
            @Parameter(description = "结束日期，格式：yyyy-MM-dd", example = "2025-01-22")
            @RequestParam(required = false) String endDate) {
        
        log.info("获取单站运行数据请求 - 电站ID: {}, 开始日期: {}, 结束日期: {}", 
                stationId, startDate, endDate);
        
        try {
            List<StationData> stationDataList;
            
            // 如果有日期范围参数，则按日期范围查询
            if (startDate != null && endDate != null) {
                stationDataList = stationDataService.getStationDataByDateRange(
                    java.time.LocalDate.parse(startDate), 
                    java.time.LocalDate.parse(endDate)
                );
                // 过滤指定电站的数据
                stationDataList = stationDataList.stream()
                    .filter(data -> stationId.equals(data.getStationId()))
                    .collect(java.util.stream.Collectors.toList());
            } else {
                // 如果没有日期范围，获取该电站的所有数据
                stationDataList = stationDataService.getStationDataByStationId(stationId);
            }
            
            Map<String, Object> response = new HashMap<>();
            
            if (stationDataList != null && !stationDataList.isEmpty()) {
                log.info("成功获取电站数据 - 电站ID: {}, 数据条数: {}", stationId, stationDataList.size());
                response.put("success", true);
                response.put("message", "获取电站数据成功");
                response.put("data", stationDataList);
                response.put("total", stationDataList.size());
                response.put("stationId", stationId);
                if (startDate != null && endDate != null) {
                    response.put("startDate", startDate);
                    response.put("endDate", endDate);
                }
            } else {
                log.warn("未找到指定的电站数据 - 电站ID: {}", stationId);
                response.put("success", false);
                response.put("message", "未找到指定的电站数据，电站ID: " + stationId);
                response.put("data", null);
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取单站运行数据失败 - 电站ID: {}, 错误信息: {}", stationId, e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取电站数据失败: " + e.getMessage());
            response.put("data", null);
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    
    /**
     * 获取电站概览数据
     */
    @GetMapping("/overview")
    @Operation(
        summary = "获取电站概览数据", 
        description = "获取所有电站的运行数据汇总，支持按具体日期过滤。日期格式为yyyy-MM-dd。当指定日期时，如果某个电站没有数据，也会在列表中显示，数据字段为空。"
    )
    @ApiOperationSupport(order = 22)
    public ResponseEntity<Map<String, Object>> getStationOverview(
            @Parameter(description = "查询日期，格式：yyyy-MM-dd", example = "2025-01-20")
            @RequestParam(required = false) String date) {
        
        log.info("获取电站概览数据请求 - 查询日期: {}", date);
        
        try {
            List<StationData> stationDataList;
            
            // 如果提供了具体日期，则按该日期查询，并包含所有电站
            if (date != null && !date.trim().isEmpty()) {
                java.time.LocalDate queryDate = java.time.LocalDate.parse(date);
                
                // 获取所有电站信息
                List<StationInfo> allStations = stationInfoService.getAllStationInfo();
                
                // 获取该日期的所有电站数据
                List<StationData> dateDataList = stationDataService.getStationDataByDateRange(queryDate, queryDate);
                
                // 创建一个 Map，用于快速查找指定电站在指定日期的数据
                Map<String, StationData> stationDataMap = new HashMap<>();
                for (StationData data : dateDataList) {
                    stationDataMap.put(data.getStationId(), data);
                }
                
                // 构建结果列表，包含所有电站
                stationDataList = new java.util.ArrayList<>();
                for (StationInfo station : allStations) {
                    StationData stationData = stationDataMap.get(station.getStationId());
                    
                    if (stationData != null) {
                        // 如果该电站有数据，直接添加
                        stationDataList.add(stationData);
                    } else {
                        // 如果该电站没有数据，创建一个空的数据对象
                        StationData emptyData = new StationData();
                        emptyData.setStationId(station.getStationId());
                        emptyData.setStationName(station.getStationName());
                        emptyData.setDataDate(queryDate);
                        // 其他字段保持为 null，表示无数据
                        stationDataList.add(emptyData);
                    }
                }
            } else {
                // 如果没有提供日期，获取所有数据
                stationDataList = stationDataService.getAllStationData();
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "获取电站概览数据成功");
            response.put("data", stationDataList);
            response.put("total", stationDataList.size());
            
            if (date != null && !date.trim().isEmpty()) {
                response.put("date", date);
            }
            
            log.info("成功获取电站概览数据，共{}条记录", stationDataList.size());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取电站概览数据失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取电站概览数据失败: " + e.getMessage());
            response.put("data", null);
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 获取电站排名数据
     */
    @GetMapping("/ranking")
    @Operation(
        summary = "获取电站排名", 
        description = "根据数据类型获取电站累计排名，支持正序和倒序。排名基于所有历史数据的累计值计算。"
    )
    @ApiOperationSupport(order = 23)
    public ResponseEntity<Map<String, Object>> getStationRanking(
            @Parameter(description = "数据类型", example = "DISCHARGE_ENERGY", required = true, schema = @Schema(allowableValues = {"DISCHARGE_ENERGY", "SYSTEM_EFFICIENCY", "CUMULATIVE_REVENUE"}))
            @RequestParam RankingDataType dataType,
            @Parameter(description = "排序方式", example = "DESC", schema = @Schema(allowableValues = {"ASC", "DESC"}))
            @RequestParam(defaultValue = "DESC") SortOrder sortOrder) {
        
        log.info("获取电站排名请求 - 数据类型: {}, 排序方式: {}", dataType, sortOrder);
        
        try {
            // 调用服务层方法获取排名数据
            List<StationRanking> rankingList = stationDataService.getStationRanking(dataType, sortOrder);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "获取电站排名成功");
            response.put("data", rankingList);
            response.put("total", rankingList.size());
            response.put("dataType", dataType);
            response.put("dataTypeDescription", dataType.getDescription());
            response.put("sortOrder", sortOrder);
            response.put("sortOrderDescription", sortOrder.getDescription());
            
            log.info("成功获取电站排名数据，共{}条记录", rankingList.size());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取电站排名数据失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取电站排名数据失败: " + e.getMessage());
            response.put("data", null);
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 获取仪表板数据
     */
    @GetMapping("/dashboard")
    @Operation(
        summary = "获取仪表板数据", 
        description = "获取电站分布、电站状态和工单状态的综合数据，用于仪表板展示"
    )
    @ApiOperationSupport(order = 24)
    public ResponseEntity<Map<String, Object>> getDashboardData() {
        log.info("获取仪表板数据请求");
        
        try {
            // 调用服务层方法获取仪表板数据
            DashboardData dashboardData = stationDataService.getDashboardData();
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "获取仪表板数据成功");
            response.put("data", dashboardData);
            
            log.info("成功获取仪表板数据");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取仪表板数据失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取仪表板数据失败: " + e.getMessage());
            response.put("data", null);
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 根据电站ID和月份获取数据
     */
    @GetMapping("/{stationId}/monthly")
    @Operation(
        summary = "获取电站月度数据", 
        description = "根据电站ID和月份获取该电站某月的所有数据。月份格式为yyyy-MM。"
    )
    @ApiOperationSupport(order = 25)
    public ResponseEntity<Map<String, Object>> getStationMonthlyData(
            @Parameter(description = "电站ID", required = true, example = "ST001")
            @PathVariable String stationId,
            @Parameter(description = "月份，格式：yyyy-MM", required = true, example = "2025-01")
            @RequestParam String month) {
        
        log.info("获取电站月度数据请求 - 电站ID: {}, 月份: {}", stationId, month);
        
        try {
            // 解析月份参数
            String[] parts = month.split("-");
            if (parts.length != 2) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "月份格式错误，正确格式为：yyyy-MM");
                response.put("data", null);
                return ResponseEntity.badRequest().body(response);
            }
            
            int year = Integer.parseInt(parts[0]);
            int monthValue = Integer.parseInt(parts[1]);
            
            if (monthValue < 1 || monthValue > 12) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "月份必须在1-12之间");
                response.put("data", null);
                return ResponseEntity.badRequest().body(response);
            }
            
            // 查询数据
            List<StationData> stationDataList = stationDataService.getStationDataByStationIdAndMonth(
                stationId, year, monthValue);
            
            Map<String, Object> response = new HashMap<>();
            
            if (stationDataList != null && !stationDataList.isEmpty()) {
                log.info("成功获取电站月度数据 - 电站ID: {}, 月份: {}, 数据条数: {}", 
                    stationId, month, stationDataList.size());
                response.put("success", true);
                response.put("message", "获取电站月度数据成功");
                response.put("data", stationDataList);
                response.put("total", stationDataList.size());
                response.put("stationId", stationId);
                response.put("year", year);
                response.put("month", monthValue);
            } else {
                log.warn("未找到指定的电站月度数据 - 电站ID: {}, 月份: {}", stationId, month);
                response.put("success", false);
                response.put("message", "未找到指定的电站月度数据，电站ID: " + stationId + ", 月份: " + month);
                response.put("data", null);
            }
            
            return ResponseEntity.ok(response);
        } catch (NumberFormatException e) {
            log.error("月份参数解析失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "月份格式错误，正确格式为：yyyy-MM");
            response.put("data", null);
            return ResponseEntity.badRequest().body(response);
        } catch (Exception e) {
            log.error("获取电站月度数据失败 - 电站ID: {}, 月份: {}, 错误信息: {}", 
                stationId, month, e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取电站月度数据失败: " + e.getMessage());
            response.put("data", null);
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 新增电站运行数据
     */
    @PostMapping("/data")
    @Operation(
        summary = "新增电站运行数据", 
        description = "新增一条电站运行数据记录，需要提供电站ID、数据日期和各项运行指标"
    )
    @ApiOperationSupport(order = 26)
    public ResponseEntity<Map<String, Object>> createStationData(
            @io.swagger.v3.oas.annotations.parameters.RequestBody(
                description = "电站数据新增请求参数",
                required = true
            )
            @RequestBody StationDataCreateRequest request) {
        
        log.info("新增电站运行数据请求 - 电站ID: {}, 数据日期: {}", 
            request.getStationId(), request.getDataDate());
        
        try {
            // 参数校验
            if (request.getStationId() == null || request.getStationId().trim().isEmpty()) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "电站ID不能为空");
                response.put("data", null);
                return ResponseEntity.badRequest().body(response);
            }
            
            if (request.getDataDate() == null || request.getDataDate().trim().isEmpty()) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "数据日期不能为空");
                response.put("data", null);
                return ResponseEntity.badRequest().body(response);
            }
            
            // 验证电站是否存在
            StationInfo stationInfo = stationInfoService.getStationInfoByStationId(request.getStationId());
            if (stationInfo == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "电站不存在，电站ID: " + request.getStationId());
                response.put("data", null);
                return ResponseEntity.badRequest().body(response);
            }
            
            // 解析日期
            LocalDate date = LocalDate.parse(request.getDataDate());
            
            // 验证日期不能是未来日期
            if (date.isAfter(LocalDate.now())) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "数据日期不能是未来日期");
                response.put("data", null);
                return ResponseEntity.badRequest().body(response);
            }
            
            // 构建电站数据对象
            StationData stationData = new StationData();
            stationData.setStationId(request.getStationId());
            stationData.setStationName(stationInfo.getStationName());
            stationData.setDataDate(date);
            stationData.setGridUploadPower(request.getGridUploadPower());
            stationData.setGridDownloadPower(request.getGridDownloadPower());
            stationData.setPcsEfficiency(request.getPcsEfficiency());
            stationData.setCircuitEfficiency(request.getCircuitEfficiency());
            stationData.setEquivalentCycles(request.getEquivalentCycles());
            stationData.setRevenue(request.getRevenue());
            stationData.setDataSource(DataSourceType.MANUAL_CREATED); // 标记为手动添加
            
            // 保存数据
            boolean success = stationDataService.saveStationData(stationData);
            
            Map<String, Object> response = new HashMap<>();
            if (success) {
                log.info("成功新增电站运行数据 - 电站ID: {}, 数据日期: {}", 
                    request.getStationId(), request.getDataDate());
                response.put("success", true);
                response.put("message", "新增电站运行数据成功");
                response.put("data", stationData);
                return ResponseEntity.ok(response);
            } else {
                log.error("新增电站运行数据失败 - 电站ID: {}, 数据日期: {}", 
                    request.getStationId(), request.getDataDate());
                response.put("success", false);
                response.put("message", "新增电站运行数据失败");
                response.put("data", null);
                return ResponseEntity.internalServerError().body(response);
            }
        } catch (Exception e) {
            log.error("新增电站运行数据异常 - 错误信息: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "新增电站运行数据失败: " + e.getMessage());
            response.put("data", null);
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 修改电站运行数据
     */
    @PutMapping("/data/{id}")
    @Operation(
        summary = "修改电站运行数据", 
        description = "根据数据ID修改电站运行数据记录，只更新提供的字段"
    )
    @ApiOperationSupport(order = 27)
    public ResponseEntity<Map<String, Object>> updateStationData(
            @Parameter(description = "数据ID", required = true, example = "1")
            @PathVariable Long id,
            @io.swagger.v3.oas.annotations.parameters.RequestBody(
                description = "电站数据修改请求参数（只更新提供的字段）",
                required = true
            )
            @RequestBody StationDataUpdateRequest request) {
        
        log.info("修改电站运行数据请求 - 数据ID: {}", id);
        
        try {
            // 先查询原数据是否存在
            StationData existingData = stationDataService.getAllStationData()
                .stream()
                .filter(data -> data.getId().equals(id))
                .findFirst()
                .orElse(null);
            
            if (existingData == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "数据不存在，数据ID: " + id);
                response.put("data", null);
                return ResponseEntity.badRequest().body(response);
            }
            
            // 更新字段（只更新非空参数）
            if (request.getStationId() != null && !request.getStationId().trim().isEmpty()) {
                // 验证电站是否存在
                StationInfo stationInfo = stationInfoService.getStationInfoByStationId(request.getStationId());
                if (stationInfo == null) {
                    Map<String, Object> response = new HashMap<>();
                    response.put("success", false);
                    response.put("message", "电站不存在，电站ID: " + request.getStationId());
                    response.put("data", null);
                    return ResponseEntity.badRequest().body(response);
                }
                existingData.setStationId(request.getStationId());
                existingData.setStationName(stationInfo.getStationName());
            }
            
            if (request.getDataDate() != null && !request.getDataDate().trim().isEmpty()) {
                LocalDate date = LocalDate.parse(request.getDataDate());
                // 验证日期不能是未来日期
                if (date.isAfter(LocalDate.now())) {
                    Map<String, Object> response = new HashMap<>();
                    response.put("success", false);
                    response.put("message", "数据日期不能是未来日期");
                    response.put("data", null);
                    return ResponseEntity.badRequest().body(response);
                }
                existingData.setDataDate(date);
            }
            
            if (request.getGridUploadPower() != null) {
                existingData.setGridUploadPower(request.getGridUploadPower());
            }
            
            if (request.getGridDownloadPower() != null) {
                existingData.setGridDownloadPower(request.getGridDownloadPower());
            }
            
            if (request.getPcsEfficiency() != null) {
                existingData.setPcsEfficiency(request.getPcsEfficiency());
            }
            
            if (request.getCircuitEfficiency() != null) {
                existingData.setCircuitEfficiency(request.getCircuitEfficiency());
            }
            
            if (request.getEquivalentCycles() != null) {
                existingData.setEquivalentCycles(request.getEquivalentCycles());
            }
            
            if (request.getRevenue() != null) {
                existingData.setRevenue(request.getRevenue());
            }
            
            // 标记为手动修改
            existingData.setDataSource(DataSourceType.MANUAL_UPDATED);
            
            // 更新数据
            boolean success = stationDataService.updateStationData(existingData);
            
            Map<String, Object> response = new HashMap<>();
            if (success) {
                log.info("成功修改电站运行数据 - 数据ID: {}", id);
                response.put("success", true);
                response.put("message", "修改电站运行数据成功");
                response.put("data", existingData);
                return ResponseEntity.ok(response);
            } else {
                log.error("修改电站运行数据失败 - 数据ID: {}", id);
                response.put("success", false);
                response.put("message", "修改电站运行数据失败");
                response.put("data", null);
                return ResponseEntity.internalServerError().body(response);
            }
        } catch (Exception e) {
            log.error("修改电站运行数据异常 - 数据ID: {}, 错误信息: {}", 
                id, e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "修改电站运行数据失败: " + e.getMessage());
            response.put("data", null);
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
}
